#include "pin.h"
#include "exceptions.h"

#include <QDebug>

void Pin::init()
{
    this->defaultSignal = -1;
    this->outEnabled = true;
    this->type = PinType_In;
    this->signal = -1;
    this->friendPIN = NULL;

    this->activeRegion.topLeftPoint.setX(0);
    this->activeRegion.topLeftPoint.setY(0);
    this->activeRegion.bindPoint.setX(0);
    this->activeRegion.bindPoint.setY(0);

    this->activeRegion.width = 0;
    this->activeRegion.height = 0;
}

Pin::Pin()
{
    init();
}

Pin::Pin(BaseElement *parent)
{
    init();
    this->parentElement = parent;
}

Pin::~Pin()
{

}

void Pin::send(signed char signal)
{
    this->signal = signal;
    this->ticTime++;
    if (this->friendPIN)
    {
        if (this->outEnabled)
        {
            this->friendPIN->receive(signal);
        }
    }
    emit onSend(this,signal);
}

void Pin::receive(signed char signal)
{
    if (this->type == PinType_Out && this->outEnabled)
        throw SignalException(this);
    this->signal = signal;
    this->ticTime++;
    emit onReceive(this,signal);
}

void Pin::reset()
{
    this->signal = this->defaultSignal;
}

void Pin::disconnectPin()
{
    if (this->friendPIN != NULL)
    {
        this->friendPIN->friendPIN = NULL;
        this->friendPIN = NULL;
    }
}

void Pin::connectPin(Pin *pin)
{
    if (pin != NULL)
    {
        pin->friendPIN = this;
        this->friendPIN = pin;
    }
}

void Pin::unite(Pin *one, Pin *two)
{
    if ((one != NULL) && (two != NULL))
    {
        one->friendPIN = two;
        two->friendPIN = one;
    }
}

void Pin::dropEvents()
{
    disconnect(this, SIGNAL(onSend(signed char)), 0, 0);
    disconnect(this, SIGNAL(onReceive(signed char)), 0, 0);
}

QString Pin::typeToString()
{
    switch (type)
    {
        case PinType_In:
            return "In";
        case PinType_Out:
            return "Out";
        case PinType_Other:
            return "Other";
    }
    return "None";
}
